<?php

namespace App\Models;

class Buys extends Base
{

    /**
     * 得到所购买的id和数量
     */
    protected function parseItems($order_info)
    {
        //存放所购商品ID和数量组成的键值对
        $buy_items = [];
        if (is_array($order_info)) {
            foreach ($order_info as $key => $value) {
                $buy_items[$value['id']] = $value['num'];
            }
        }
        return $buy_items;
    }

    /**
     * (直接购买)取最新的在售商品信息（需要在售）
     * @param int $goods_id 所购商品ID
     * @param int $buy_num 购买数量
     * @return array
     */
    protected function getGoodsOnlineInfo($goods_id, $buy_num)
    {
        //取目前在售商品
        $goods_info = Goods::details(['id'=>$goods_id]);
        if (empty($goods_info) || $goods_info['status'] != 1) {
            return null;
        }
        $new_array = [];
        $new_array['goods_num'] = $buy_num;
        $new_array['store_id'] = $goods_info['store_id'];
        $new_array['store_name'] = $goods_info['store_name'];
        $new_array['goods_id'] = $goods_id;
        $new_array['goods_name'] = $goods_info['title'];
        $new_array['goods_price'] = $goods_info['price'];
        $new_array['goods_img'] = $goods_info['thumb'];
        $new_array['goods_freight'] = $goods_info['freight'];
        $new_array['goods_storage'] = $goods_info['storage'];
        $new_array['goods_type'] = $goods_info['type'];
//        $new_array['state'] = true;
//        $new_array['storage_state'] = intval($goods_info['storage']) < intval($buy_num) ? false : true;
        //填充必要下标，方便后面统一使用购物车方法与模板
        $new_array['cart_id'] = $goods_id;
        return $new_array;
    }

    /**
     * (购物车购买)取商品最新的在售信息
     * @param unknown $cart_list
     * @return array
     */
    protected function getCartOnlineList($cart_list)
    {
        if (empty($cart_list)) return $cart_list;
        //验证商品是否有效
        $goods_id_array = [];
        foreach ($cart_list as $key => $cart_info) {
            $goods_id_array[] = $cart_info['goods_id'];
        }
        $goods_online_list = Goods::getGoodsOnlineListAndPromotionByIdArray($goods_id_array);
        $goods_online_array = array();
        foreach ($goods_online_list as $goods) {
            $goods_online_array[$goods['id']] = $goods;
        }
        foreach ($cart_list as $key => $cart_info) {
//            $cart_list[$key]['state'] = true;
//            $cart_list[$key]['storage_state'] = true;
            if (in_array($cart_info['goods_id'], array_keys($goods_online_array))) {
                $goods_online_info = $goods_online_array[$cart_info['goods_id']];
                $cart_list[$key]['goods_name'] = $goods_online_info['title'];
                $cart_list[$key]['goods_img'] = $goods_online_info['thumb'];
                $cart_list[$key]['goods_price'] = $goods_online_info['price'];
                $cart_list[$key]['goods_freight'] = $goods_online_info['freight'];
                $cart_list[$key]['goods_storage'] = $goods_online_info['storage'];
                $cart_list[$key]['goods_num'] = $cart_info['num'];
                $cart_list[$key]['goods_type'] = $goods_online_info['type'];
//                if ($cart_info['num'] > $goods_online_info['storage']) {
//                    $cart_list[$key]['storage_state'] = false;
//                }
            }else {
                //如果商品下架
//                $cart_list[$key]['state'] = false;
//                $cart_list[$key]['storage_state'] = false;
            }
        }
        return $cart_list;
    }

    /**
     * 商品金额计算(分别对每个商品/优惠套装小计、每个店铺小计)
     * @param unknown $store_cart_list 以店铺ID分组的购物车商品信息
     * @return array
     */
    protected function calcCartList($store_cart_list)
    {
        if (empty($store_cart_list)) return $store_cart_list;

        $store_goods_total = [];//存放每个店铺的商品总金额
        $store_freight_total = [];//存放每个店铺的商品总金额
        $store_goods_amount = [];//存放商品总金额
        foreach ($store_cart_list as $store_id => $store_cart) {
            $tmp_amount = 0;//当前订单总价
            $freight_amount = 0;//当前总邮费
            $goods_amount = 0;//当前商品总价
            foreach ($store_cart['goods_list'] as $key => $cart_info) {
                $store_cart['goods_list'][$key]['goods_total'] = $this->ds_price_format($cart_info['goods_price'] * $cart_info['goods_num']);
                $store_cart['goods_list'][$key]['goods_amounts'] = $this->ds_price_format($cart_info['goods_price'] * $cart_info['goods_num'] + $cart_info['goods_freight']);
                $tmp_amount += $store_cart['goods_list'][$key]['goods_amounts'];
                $freight_amount += $store_cart['goods_list'][$key]['goods_freight'];
                $goods_amount += $store_cart['goods_list'][$key]['goods_total'];
            }
            $store_cart_list[$store_id] = $store_cart;
            $store_goods_total[$store_id] = $this->ds_price_format($tmp_amount);
            $store_freight_total[$store_id] = $this->ds_price_format($freight_amount);
            $store_goods_amount[$store_id] = $this->ds_price_format($goods_amount);
        }
        return [$store_cart_list, $store_goods_total, $store_freight_total,$store_goods_amount];
    }

    /**
     * 判断库存
     * @param array $store_cart_list 购买列表
     */
    protected function appendPremiumsToCartList($store_cart_list)
    {
        if (empty($store_cart_list)) return [];
        //取得每种商品的库存[含赠品]
        $goods_storage_quantity = $this->_getEachGoodsStorageQuantity($store_cart_list);
        //取得每种商品的购买量[不含赠品]
        $goods_buy_quantity = $this->_getEachGoodsBuyQuantity($store_cart_list);
        foreach ($goods_buy_quantity as $goods_id => $quantity) {
            $goods_storage_quantity[$goods_id] -= $quantity;
            if ($goods_storage_quantity[$goods_id] < 0) {
                //商品库存不足，请重购买
                return false;
            }
        }
        return array($store_cart_list, $goods_buy_quantity);
    }

    /**
     * 取得每种商品的库存
     * @param array $store_cart_list 购买列表
     * @param array $store_premiums_list 赠品列表
     * @return array 商品ID=>库存
     */
    protected function _getEachGoodsStorageQuantity($store_cart_list, $store_premiums_list = array())
    {
        if (empty($store_cart_list) || !is_array($store_cart_list))
            return array();
        $goods_storage_quangity = array();
        foreach ($store_cart_list as $store_cart) {
            foreach ($store_cart['goods_list'] as $cart_info) {
                //正常商品
                $goods_storage_quangity[$cart_info['goods_id']] = $cart_info['goods_storage'];
            }
        }
        //取得赠品商品的库存
        if (is_array($store_premiums_list)) {
            foreach ($store_premiums_list as $store_id => $goods_list) {
                foreach ($goods_list as $goods_info) {
                    if (!isset($goods_storage_quangity[$goods_info['goods_id']])) {
                        $goods_storage_quangity[$goods_info['goods_id']] = $goods_info['goods_storage'];
                    }
                }
            }
        }
        return $goods_storage_quangity;
    }

    /**
     * 取得每种商品的购买量
     * @param array $store_cart_list 购买列表
     * @return array 商品ID=>购买数量
     */
    protected function _getEachGoodsBuyQuantity($store_cart_list)
    {
        if (empty($store_cart_list) || !is_array($store_cart_list))
            return array();
        $goods_buy_quangity = array();
        foreach ($store_cart_list as $store_cart) {
            foreach ($store_cart['goods_list'] as $cart_info) {
                //正常商品
                if (!isset($goods_buy_quangity[$cart_info['goods_id']])){
                    $goods_buy_quangity[$cart_info['goods_id']] = $cart_info['goods_num'];
                }else {
                    $goods_buy_quangity[$cart_info['goods_id']] += $cart_info['goods_num'];
                }
            }
        }
        return $goods_buy_quangity;
    }

    /**
     * 生成20位编号(时间+微秒+随机数+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =12位 + 3位 + 2位 + 3位  = 20位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @return string
     */
    protected function makePaySn($user_id) {
        return date('ymdHis',  time()).sprintf('%03d', (float) microtime() * 1000) .mt_rand(10, 99).sprintf('%03d', intval($user_id) % 1000);
    }

    /**
     * 订单编号生成规则，n(n>=1)个订单表对应一个支付表，
     * 生成订单编号(年取1位 + $pay_id取13位 + 第N个子订单取2位)
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @param $pay_id 支付表自增ID
     * @return string
     */
    protected function makeOrderSn($pay_id)
    {
        //记录生成子订单的个数，如果生成多个子订单，该值会累加
        static $num;
        if (empty($num)) {
            $num = 1;
        }
        else {
            $num++;
        }
        return (date('y', time()) % 9 + 1) . sprintf('%013d', $pay_id) . sprintf('%02d', $num);
    }

    /**
     * 价格格式化
     *
     * @param int $price
     * @return string    $price_format
     */
    protected function ds_price_format($price)
    {
        $price_format = number_format($price, 2, '.', '');
        return $price_format;
    }
}
